package com.kunlun.basedata.service.impl;

import com.kunlun.basedata.dao.ISystemFileDao;
import com.kunlun.basedata.model.SystemFileModel;
import com.kunlun.basedata.model.UserModel;
import com.kunlun.basedata.model.vo.SystemFileVo;
import com.kunlun.basedata.service.ISystemFileService;
import com.kunlun.basedata.service.IUserService;
import com.kunlun.common.model.Context;
import com.kunlun.common.model.CurrentAccount;
import com.kunlun.common.model.Page;
import com.kunlun.common.utils.CommonUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SystemFileService implements ISystemFileService {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private ISystemFileDao systemFileDao;

    @Override
    public Page<SystemFileVo> getAllFiles(SystemFileVo systemFileVo, int currentPage, int pageSize) throws Exception {
        int startIndex = (currentPage - 1) * pageSize;
        Map<String, Object> queryMap = CommonUtil.packageQueryMap(systemFileVo, startIndex, pageSize);

        Page page = new Page();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        page.setTotal(systemFileDao.getFilesCount(queryMap));
        page.setRecords(systemFileDao.getAllFiles(queryMap));
        return page;
    }

    @Override
    public void onUpload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        CurrentAccount currentAccount = Context.getCurrentAccount();
        Date date = new Date();
        SystemFileModel fileModel = new SystemFileModel();
        fileModel.setId(CommonUtil.generateUUID());
        fileModel.setName(file.getOriginalFilename());
        fileModel.setType(file.getContentType());
        fileModel.setSize(String.valueOf(file.getSize()));
        fileModel.setUserId(currentAccount.getUserId());
        fileModel.setBase64(generateBase64(inputStream));
        fileModel.setCreateTime(date);
        fileModel.setModifiedTime(date);
        systemFileDao.addFile(fileModel);
        inputStream.close();
    }

    @Override
    public void onDelete(String ids) throws Exception {
        List<String> listIds = Arrays.asList(ids.split(","));
        systemFileDao.onDelete(listIds);
    }

    private String generateBase64(InputStream inputStream) {
        byte[] data = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buffer, 0, 100)) > 0) {
                byteArrayOutputStream.write(buffer, 0, rc);
            }
            data = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            logger.error("transfer base64 error: ", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("close base64 stream error: ", e);
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }
}
